# paper_list.py
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QTableWidget, QTableWidgetItem,
                             QPushButton, QHeaderView, QMessageBox, QInputDialog, QLineEdit, QLabel)
from database import get_exams, delete_exam, search_exams, update_exam_name, get_exam, \
    get_db_connection  # 需要确保数据库存在这些方法
from papers_dialog import PaperPreviewDialog, PaperPreviewDialog2


class PaperListWidget(QWidget):
    refresh_requested = pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.current_page = 1  # 新增：当前页码
        self.page_size = 15     # 新增：每页显示数量
        self.total_pages = 1    # 新增：总页数
        self.current_exams = []  # 当前试卷列表
        self.is_search_mode = False  # 新增：标识是否处于搜索模式
        self.init_ui()
        self.load_data()  # 页面进入时自动刷新页面

    def init_ui(self):
        layout = QVBoxLayout()

        # 搜索栏和搜索按钮
        search_layout = QHBoxLayout()
        self.search_bar = QLineEdit()
        self.search_bar.setPlaceholderText("输入试卷名称搜索...")
        search_layout.addWidget(self.search_bar)

        self.search_btn = QPushButton("搜索")
        self.search_btn.clicked.connect(self.search_exams)  # 确保按钮点击触发搜索
        search_layout.addWidget(self.search_btn)
        layout.addLayout(search_layout)

        # 试卷表格
        self.table = QTableWidget()
        self.table.setColumnCount(5)
        self.table.setHorizontalHeaderLabels(["ID", "试卷名称", "题目数量", "创建时间", "操作"])
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table.verticalHeader().setVisible(False)
        self.table.setEditTriggers(QTableWidget.NoEditTriggers)
        layout.addWidget(self.table)
        self.setLayout(layout)
        # 新增分页控件
        self.pagination_layout = QHBoxLayout()
        self.prev_btn = QPushButton("上一页")
        self.prev_btn.clicked.connect(self.prev_page)
        self.page_label = QLabel("1/1")
        self.next_btn = QPushButton("下一页")
        self.next_btn.clicked.connect(self.next_page)
        self.pagination_layout.addStretch()
        self.pagination_layout.addWidget(self.prev_btn)
        self.pagination_layout.addWidget(self.page_label)
        self.pagination_layout.addWidget(self.next_btn)
        self.pagination_layout.addStretch()
        layout.addLayout(self.pagination_layout)

    def load_data(self):
        """带分页的加载方法"""
        # 获取总记录数
        if self.is_search_mode:
            total = len(self.current_exams)  # 搜索模式下使用当前搜索结果的总数
        else:
            total = self.get_total_count()

        self.total_pages = max(1, (total + self.page_size - 1) // self.page_size)

        # 获取分页数据
        if self.is_search_mode:
            start = (self.current_page - 1) * self.page_size
            end = start + self.page_size
            self.current_exams = self.current_exams[start:end]
        else:
            self.current_exams = get_exams(
                page=self.current_page,
                page_size=self.page_size
            )

        # 更新分页状态
        self.update_pagination()

        # 渲染表格
        self.render_table()

        # 设置行高
        self.table.verticalHeader().setDefaultSectionSize(40)  # 行高设为40像素

    def render_table(self):
        """渲染表格内容"""
        self.table.setRowCount(len(self.current_exams))
        for row, exam in enumerate(self.current_exams):
            # 渲染ID
            id_item = QTableWidgetItem(exam['id'])
            id_item.setTextAlignment(Qt.AlignCenter)
            self.table.setItem(row, 0, id_item)

            # 渲染试卷名称
            name_item = QTableWidgetItem(exam['title'])
            name_item.setTextAlignment(Qt.AlignCenter)
            self.table.setItem(row, 1, name_item)

            # 渲染题目数量
            count_item = QTableWidgetItem(str(exam['question_count']))
            count_item.setTextAlignment(Qt.AlignCenter)
            self.table.setItem(row, 2, count_item)

            # 渲染创建时间
            created_at = exam['created_at']
            if isinstance(created_at, str):  # 判断是否为字符串
                created_at = created_at  # 直接使用字符串
            elif created_at:  # 如果是 datetime 对象
                created_at = created_at.strftime('%Y-%m-%d %H:%M:%S')
            else:
                created_at = ''  # 如果为空
            created_item = QTableWidgetItem(created_at)
            created_item.setTextAlignment(Qt.AlignCenter)
            self.table.setItem(row, 3, created_item)

            # 渲染操作按钮
            btn_layout = QHBoxLayout()
            btn_layout.setContentsMargins(0, 0, 0, 0)
            btn_layout.setSpacing(5)  # 设置按钮之间的间距

            # 创建按钮并设置样式
            edit_btn = self.create_button("重命名", lambda _, eid=exam['id']: self.edit_exam(eid), "#2196F3")
            delete_btn = self.create_button("删除", lambda _, eid=exam['id']: self.delete_exam(eid), "#F44336")
            preview_btn = self.create_button("预览", lambda _, eid=exam['id']: self.preview_exam(eid), "#4CAF50")

            # 将按钮添加到布局中
            btn_layout.addWidget(edit_btn)
            btn_layout.addWidget(delete_btn)
            btn_layout.addWidget(preview_btn)

            # 创建一个容器 Widget 并设置布局
            cell_widget = QWidget()
            cell_widget.setLayout(btn_layout)
            self.table.setCellWidget(row, 4, cell_widget)

            # 设置具体行高（可选）
            self.table.setRowHeight(row, 40)

    # 修改 create_button 方法以支持不同颜色和宽度
    def create_button(self, text, callback, color):
        """创建按钮并设置样式"""
        btn = QPushButton(text)
        btn.setStyleSheet(f"""
            QPushButton {{
                background-color: {color};
                color: white;
                border: none;
                padding: 5px 10px;
                border-radius: 5px;
                font-size: 12px;
                min-width: 50px;  /* 新增：确保最小宽度 */
                max-width: 50px;  /* 新增：确保最大宽度 */
            }}
            QPushButton:hover {{
                background-color: {self.darken_color(color)};
            }}
        """)
        btn.setFixedWidth(50)  # 确保宽度设置生效
        btn.setFixedHeight(30)  # 设置固定高度
        btn.clicked.connect(callback)
        return btn

    # 新增方法：深色化颜色值
    def darken_color(self, color):
        """将颜色值变暗 10%"""
        r, g, b = int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)
        r = max(0, r - 25)
        g = max(0, g - 25)
        b = max(0, b - 25)
        return f"#{r:02X}{g:02X}{b:02X}"

    # 新增分页相关方法
    def get_total_count(self):
        """获取总记录数"""
        conn = get_db_connection()
        try:
            cursor = conn.execute("SELECT COUNT(*) FROM exams")
            return cursor.fetchone()[0]
        finally:
            conn.close()

    def update_pagination(self):
        """更新分页控件状态"""
        self.page_label.setText(f"{self.current_page}/{self.total_pages}")
        self.prev_btn.setEnabled(self.current_page > 1)
        self.next_btn.setEnabled(self.current_page < self.total_pages)

    def prev_page(self):
        if self.current_page > 1:
            self.current_page -= 1
            self.load_data()

    def next_page(self):
        if self.current_page < self.total_pages:
            self.current_page += 1
            self.load_data()

    def search_exams(self):
        """搜索试卷并同步更新表格数据"""
        keyword = self.search_bar.text().strip()
        if keyword:
            # 如果关键字不为空，执行搜索
            self.current_exams = search_exams(keyword)
            self.is_search_mode = True  # 进入搜索模式
        else:
            # 如果关键字为空，退出搜索模式，加载所有试卷
            self.is_search_mode = False
            self.current_exams = get_exams(page=self.current_page, page_size=self.page_size)
        self.current_page = 1  # 搜索时重置到第一页
        self.load_data()  # 确保搜索后重新加载数据

    def delete_exam(self, exam_id):
        """删除试卷"""
        reply = QMessageBox.question(
            self, '确认删除',
            '确定要删除这个试卷吗？该操作不可恢复！',
            QMessageBox.Yes | QMessageBox.No
        )
        if reply == QMessageBox.Yes:
            if delete_exam(exam_id):
                self.current_page = max(1, self.current_page - 1)  # 确保删除后不会出现空白页
                self.load_data()
                QMessageBox.information(self, "成功", "试卷已删除")
                self.refresh_requested.emit()  # 触发刷新信号
            else:
                QMessageBox.warning(self, "错误", "删除失败")

    def edit_exam(self, exam_id):
        """编辑试卷名称"""
        exam = next((e for e in self.current_exams if e['id'] == exam_id), None)
        if not exam:
            return

        new_name, ok = QInputDialog.getText(
            self, '修改名称',
            '输入新名称：',
            text=exam['title']
        )
        if ok and new_name.strip():
            # 更新数据库
            if update_exam_name(exam_id, new_name):  # 需要实现update_exam_name方法
                self.load_data()
                QMessageBox.information(self, "成功", "名称已修改")
                self.refresh_requested.emit()
            else:
                QMessageBox.warning(self, "错误", "修改失败")

    def preview_exam(self, exam_id):
        """预览试卷"""
        exam = get_exam(exam_id)  # 需要实现获取单个试卷的方法
        if exam:
            dialog = PaperPreviewDialog2(exam['questions'], self)
            dialog.exec_()

